package com.lanhai.system;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.lanhai.Main;
import com.lanhai.MainAction;
import com.lanhai.action.TaskAction;

/**
 * 监听UDP端口
 * @author liangmin
 *
 */
public class Accept4Park implements Runnable {
	
	private MainAction mainAction;
	private int port;
	public static DatagramSocket ds = null;
	public Accept4Park(MainAction mainAction, int port){
		this.mainAction = mainAction;
		this.port = port;
	}
	
	/**
	 * 发送数据,有监听的端口发送
	 * @param data
	 * @param ipAddress
	 * @param port
	 */
	public static void sendData(DatagramPacket dp) {
		try {
			ds.send(dp);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run() {
		
		try{
			InetAddress is = InetAddress.getByName(Main.localStationIpAddress);
//			ds = new DatagramSocket(port,is);
			ds = new DatagramSocket(port);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("已经运行了一个实例，退出!");
			System.exit(0);
		}
		boolean isReceive = true;
		while(isReceive){
			try{
				byte buf[] = new byte[16];
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				ds.receive(dp);
//				String dataStr = HexUtil.byte2HexStr(buf);
//				System.out.println("Machine:" + dataStr);
//				System.out.println("line:" + buf[0] + ",action:" + buf[1] + ",type:" + buf[2]);
				TaskAction taskAction = mainAction.taskAction;
				String ip = dp.getAddress().getHostAddress();
				int ports = dp.getPort();
//				System.out.println("发送端端口号" + ports);
				taskAction.handle(buf, ip,ports);	
			}catch(Exception e){
				e.printStackTrace();
				isReceive = false;
			}
		}
		ds.close();
		System.out.println("UDP" + port + "端口关闭！！！");
	}
}
